﻿
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;

public class TapTimingView : MonoBehaviour
{
    public GameObject DefaultButtonDock;
    public GameObject TapTimingButtonDock;
    public Button ClaimButton;
    public Transform Arrow;
    public float MinPos;
    public float MaxPos;
    public int Steps;
    public TextMeshProUGUI Text;
    public TextMeshProUGUI defaultMultiText;
    private float _pos = 0.5f;
    private bool _reverse = false;
    private bool _stop = false;

    private Action<int> _callback;

    bool IsRewardedVideoAvailable => true;

    public void Show(int defauleMulti,Action<int> onClick)
    {
        _pos = 0.5f;
        _stop = false;
        _reverse = true;
        _callback = onClick;
        ClaimButton.enabled = true;
        this.defaultMultiText.text = $"Claim X{defauleMulti}";

        if (IsRewardedVideoAvailable)
        {
            TapTimingButtonDock.SetActive(true);
            DefaultButtonDock.SetActive(false);
        }
        else
        {
            TapTimingButtonDock.SetActive(false);
            DefaultButtonDock.SetActive(true);
        }

    }

    private void Update()
    {
        if (_stop)
            return;
        
        if (_reverse)
        {
            _pos -= Time.deltaTime;
            if (_pos <= 0)
            {
                _pos = -_pos;
                _reverse = !_reverse;
            }
        }
        else
        {
            _pos += Time.deltaTime;
            if (_pos >= 1)
            {
                _pos = _pos - (_pos - 1);
                _reverse = !_reverse;
            }
        }

        float posSQR = _pos;//(_pos * _pos);
        float finalPos = Mathf.Lerp(MinPos, MaxPos, posSQR);
        Arrow.transform.localPosition = new Vector3(finalPos, 0, 0);

        Text.text = string.Format("Claim X{0}", GetMultiply());

    }

    private int GetMultiply()
    {
        if (_pos == 0.5f) // just in case
            _pos = 0.49f;
        float posToCompare = (_pos > 0.5f ? (0.5f - (_pos - 0.5f)) : _pos) * 2;
        int multiply = 2 + Mathf.FloorToInt(posToCompare * Steps);
        return multiply;
    }

    public void Stop()
    {
        ClaimButton.enabled = false;
        _stop = true;
        _callback?.Invoke(GetMultiply());
        TapTimingButtonDock.SetActive(false);
    }
}
